package com.yuyou.fn.exception;

import com.github.wens.mybatisplus.toolkit.IdWorker;
import com.yuyou.fn.common.exception.BusException;
import com.yuyou.fn.common.util.Utils;
import com.yuyou.fn.controller.ReturnResult;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

/**
 * Created by wens on 2017/2/19.
 */
public class DefaultExceptionResolver implements HandlerExceptionResolver {

    private final Logger logger = LoggerFactory.getLogger(DefaultExceptionResolver.class);

    @Override
    public ModelAndView resolveException(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception ex) {
        String requestId = (String) httpServletRequest.getAttribute("requestId");
        logger.error("Request Fail:[url=" + httpServletRequest.getRequestURI() + ",params=" + requestParams(httpServletRequest) + ",requestId=" + requestId + "]", ex);
        httpServletResponse.setContentType("application/json;charset=UTF-8");
        try {
            PrintWriter writer = httpServletResponse.getWriter();
            if(ex instanceof BusException){
                BusException e = (BusException) ex ;
                writer.write(ReturnResult.fail(e.getMessage()).toJsonString());
            }else{
                writer.write(ReturnResult.fail("Server Error["+requestId+"]").toJsonString());
            }
            return new ModelAndView();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    private String requestParams(HttpServletRequest request) {
        Map parameterMap = request.getParameterMap();
        List<String> params = new ArrayList<>(parameterMap.size());
        for(Object key  : parameterMap.keySet() ){
            StringBuilder sb  = new StringBuilder(10) ;
            Object o = parameterMap.get(key);
            sb.append(key).append("=").append(o.getClass().isArray() ? Arrays.toString((Object[]) o) : o );
            params.add(sb.toString());
        }
        return StringUtils.join(params,",") ;
    }
}
